﻿//
// main entry
define(function (require) {
    // 检测没有登录就跳转
    require('ezdesk/utility/test-login');
    require('ezdesk/utility/window-drag');
    require('ezdesk/utility/window-resize');

    var iContentMap = {
        "feed": "i-feed",
        "app": "i-app",
        "workitem": "i-workitem",
        "project": "i-project",
        "notification": "i-notification"
    };

    var functionMenu = {
        feedItems: [
            { url: '/message/send', title: '写消息', image: 'style/images/add.png' },
        ],
        workitemItems: [
            { url: '/project/workitemList#create', title: '添加任务', image: 'style/images/add.png' },
            //{ url: '/project/workitemlist', title: '任务列表', image: 'style/images/list_bullets.png' },
        ],
        projectItems: [
            { url: '/project/projectList#create', title: '添加项目', image: 'style/images/add.png' },
            //{ url: '/project/projectList', title: '项目列表', image: 'style/images/list_bullets.png' },
        ]
    };



    // 处理 main 窗体的改变大小的事情
    $('#main').resizable({
        minHeight: 652,
        minWidth: 355,
        resize: function (event, ui) {
            setInterval(function () {   

                //navBar and conten width
                $('#i-nav-bar').width($('#main').width());
                $('.i-content').width($('#main').width());
                //conten height
                var content = $(".i-content").contents().find(".content");
                content.height(
                    $('#main').height() - $('#i-nav-bar').height() - $('#title-bar').height() - $('#footer').height()
                );
                $(".i-content").height(content.height() - 5);
                //messageAction
                $('#action-message').width($('#main').width() - 12); //12 is padding
            }, 50);
        }
    });


    $(function () {
        var service = require('ezdesk/utility/service');
        var utility = require('ezdesk/utility/utility.js');
        var NotificationManager = require('ezdesk/service/notification-manager');
        var baseUrl = service.ClientBaseUrl_CacheSync();

        service.UserHasPermission(function (e) {
            var hasCreateProjectPermission = e;
            if (!hasCreateProjectPermission) {
                functionMenu.projectItems.splice(0, 1);
            }
        }, { permissionStr: 'PROJECT_CREATE_PROJECT' });

        service.CurrentUser(function (e) {
            $("#user-name").html(e.Name);
            $("#user-dept").html("(" + e.Dept.DeptName + ")");
            $("#user-pos").html(e.Position.Description);
            var headIconUrl = '/core/headicon/{userId}'
                .replace('{userId}', e.Id);

            $('#img-head').prop('src', headIconUrl);
        });

        service.OrganizationInfo(function (e) {
            $(".page-title").html(e.ShortName);
        });



        setMainWindowLocation();
        switchTab('feed');

        //receive Message
        $.receiveMessage(function (e) {
            var paramKeyRegex = /\w*(?=\:)/g;
            var key = paramKeyRegex.exec(e.data);
            key = key ? key[0] : e.data;
            var params = e.data.substring(key.length + 1).split('|');

            if (key == 'action')
                doAction(params[0], params[1]);
            else if (key == "tab")
                switchTab(params[0]);
            else if (key == "unreadFeeds")
                showUnreadFeedsCout(params[0]);
            else if (key == "message")
                showActionMesaage(params[0]);
            else if (key == "workitems")
                showWorkitemsCount(params[0]);
            else if (key == "refreshLatestFeeds")
                refreshLatestFeeds();
            else if (key == "app-min")
                hideAppPanel();
            else
                $.postMessage(e.data, '*', parent);

        });

        //init NotificationManager
        NotificationManager.gettingFeedsCallback = refreshLatestFeeds;
        NotificationManager.start();

        //init Event
        $('.func-min,.func-close').click(function () {
            $.postMessage('min', '*', parent);
        });

        $('.app-bar').click(function () {
            var appContent = $('#' + iContentMap['app']);
            if (appContent.is(":visible") == false) {
                $('#' + iContentMap['app']).fadeIn();
            } else {
                hideAppPanel();
            }
        })




        function hideAppPanel() {
            $('#' + iContentMap['app']).fadeOut();
        }

        function doAction(actionUrl, feedId) {
            $.ajax({
                url: actionUrl,   //接收页面
                type: 'post',      //POST方式发送数据
                async: true,
                dataType: 'json',
                success: function (e) {
                    if (e.Status == 'Success') {
                        refreshLatestFeeds();
                    } else {
                        showActionMesaage(e.Info);
                    }
                },
                data: {
                    feedId: feedId
                },
                error: function (e) {
                    showActionMesaage('操作失败');
                }
            });
        }

        function receivedNewFeedsCallback(newFeeds, feedsWithNewUpdateOn) {
            var $tabItemToShow = $('#' + iContentMap['feed']);
            $.postMessage('refreshFeeds:' + utility.toJSON(newFeeds), '*', $tabItemToShow[0].contentWindow);
            //找到notification iframe
            $.postMessage('refreshNotis:' + utility.toJSON(feedsWithNewUpdateOn), '*', window.parent.frames[3]);
        };

        function getTimemark() {
            var initDate = new Date('2000', '1', '1');
            var timeMark = localStorage.getItem('TimeMark');
            return timeMark ? timeMark : initDate.toTicks();
        }

        function setTimemark(dateTime) {
            localStorage.setItem('TimeMark', dateTime);
        }

        function refreshLatestFeeds() {
            // 通知去获取一次Feed变化
            var timemark = getTimemark();
            var _self = this;
            console.log('start to get, timemark: ' + timemark);
            service.GetFeeds(
                function (e) {
                    _self.isGettingFeeds = false;
                    if (e.length != 0) {
                        // 找出update的变化，也作为callback传回去
                        console.log('i got something, we have ' + e.length + ' more feeds.');
                        var feedsWithNewUpdateOn = _.select(e, function (feed) {
                            return feed.UpdateOn > timemark && feed.IsAvailable;
                        });
                        
                        console.log(feedsWithNewUpdateOn.length + ' popup.');
                        receivedNewFeedsCallback(e, feedsWithNewUpdateOn);

                        // 更新时间戳
                        var maxUpdateOn = _.max(e, function (item) { return item.UpdateOn }).UpdateOn;
                        var maxLastChangeOn = _.max(e, function (item) { return item.LastChangeOn }).LastChangeOn;
                        timemark = Math.max(maxLastChangeOn, maxUpdateOn);
                        setTimemark(timemark);
                    } else {
                        console.log('nothing new');
                    }
                },
                { fromTicks: timemark }
            );
        }

        function showActionMesaage(data) {
            $('#txt-message').html(data);

            $('#action-message').css({
                "margin-top": 80 + 28,
                "width": $('#main').width() - 12
            });

            $('#action-message').show();
            setTimeout(function () {
                $('#action-message').hide();
            }, 3000);

            $('#action-close').click(function () {
                $('#action-message').hide();
            });
        };

        function switchTab(tabItem) {
            $('.currentTabContent').removeClass('currentTabContent').hide();
            var $tabItemToShow = $('#' + iContentMap[tabItem]);
            $tabItemToShow.addClass('currentTabContent').show();
            $.postMessage('show', '*', $tabItemToShow[0].contentWindow);

            //addMenu
            addMenu(tabItem);
        }

        function addMenu(tabItem) {
            if ($('.menu').length > 0) {
                $('.menu').remove();
            }
            var dom = $('<div class="menu"/>').appendTo($('#footer'));

            if (tabItem == 'feed')
                utility.BottomMenu.setJDock(dom, functionMenu.feedItems);
            if (tabItem == 'workitem')
                utility.BottomMenu.setJDock(dom, functionMenu.workitemItems);
            if (tabItem == 'project') {
                utility.BottomMenu.setJDock(dom, functionMenu.projectItems);
            }
        }

        function showUnreadFeedsCout(data) {
            var container = $("#i-nav-bar").contents().find("#btn-feeds .num-label");

            if (data > 0)
                container.html(data).show();
            else
                container.hide();
        }

        function showWorkitemsCount(data) {
            var container = $("#i-nav-bar").contents().find("#btn-workitems .num-label");

            if (data > 0)
                container.html(data).show();
            else
                container.hide();

        }

        function setMainWindowLocation() {
            var windowWidth = document.documentElement.offsetWidth;
            var windowHeight = document.documentElement.offsetHeight;
            var mainHeight = $("#main").height();
            var mainWidth = $("#main").width();

            var mainTop = windowHeight / 2 - mainHeight / 2 - 100;
            mainTop = mainTop < 50 ? 50 : mainTop;

            var mainLeft = windowWidth - mainWidth - 35;
            mainLeft = mainLeft < 10 ? 10 : mainLeft;
            //centering
            $('#main').css({
                "position": "absolute",
                "top": mainTop,
                "left": mainLeft
            }).show();
        }
    })
});
